package com.mall.project.sys.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.cons.StatusCons;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.core.model.response.ApiResponses;
import com.mall.common.core.model.supers.SuperController;
import com.mall.common.security.annotation.PreAuth;
import com.mall.common.security.utils.ApiUtils;
import com.mall.project.sys.cons.MenuTypeCons;
import com.mall.project.sys.model.dto.MenuDTO;
import com.mall.project.sys.model.dto.MenuTreeDTO;
import com.mall.project.sys.model.entity.Menu;
import com.mall.project.sys.model.parm.MenuPARM;
import com.mall.project.sys.service.IMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author Sam
 * @since 2021-04-13
 */
@Api(tags = {"菜单"})
@RestController
@RequestMapping("/menu")
public class MenuRestController extends SuperController {

    @Autowired
    private IMenuService menuService;

    @PreAuth
    @ApiOperation("获取所有菜单 返回树")
    @GetMapping("/trees")
    public ApiResponses<List<MenuTreeDTO>> treeList(@RequestParam(value = "status", required = false) Integer status) {
        List<MenuTreeDTO> treeList = menuService.getTreeList(status);
        return success(treeList);
    }

    @PreAuth
    @ApiOperation(value = "条件查询菜单", response = Menu.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "菜单名称 模糊", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "菜单状态", type = "int", paramType = "query")
    })
    @GetMapping("/list")
    public ApiResponses<List<Menu>> list(@RequestParam(value = "name", required = false) String name,
                                         @RequestParam(value = "status", required = false) Integer status) {
        List<Menu> menuList = menuService.list(Wrappers.<Menu>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Menu::getName, name)
                .eq(Objects.nonNull(status), Menu::getStatus, status));
        return success(menuList);
    }

    @PreAuth
    @ApiOperation("获取登录用户权限菜单 返回树")
    @GetMapping("/localTrees")
    public ApiResponses<List<MenuTreeDTO>> localTrees() {
        List<MenuTreeDTO> menuTrees = menuService.getTreeUserPermMenus(ApiUtils.currentUid());
        return success(menuTrees);
    }

    @PreAuth
    @ApiOperation("获取登录用户权限按钮")
    @GetMapping("/localButton")
    public ApiResponses<List<String>> localButton() {
        List<String> userPermButton = menuService.getUserPermMenus(ApiUtils.currentUid(), Arrays.asList(MenuTypeCons.BUTTON))
                .stream().map(MenuTreeDTO::getPerm).collect(Collectors.toList());
        return success(userPermButton);
    }

    @PreAuth
    @ApiOperation(value = "查询角色拥有权限（包含所有权限）")
    @GetMapping("/roleMenuTree/{roleId}")
    public ApiResponses<MenuDTO> roleMenuTree(@PathVariable("roleId") String roleId) {
        List<String> checkIdList = menuService.getListByRoleId(roleId).stream().map(MenuDTO::getId).collect(Collectors.toList());
        List<MenuTreeDTO> menuTree = menuService.getTreeList(StatusCons.NORMAL);
        MenuDTO dto = new MenuDTO();
        dto.setCheckIdList(checkIdList);
        dto.setMenuTree(menuTree);
        return success(dto);
    }

    @PreAuth
    @ApiOperation("单条查询菜单")
    @GetMapping("/{roleId}")
    public ApiResponses<Menu> getById(@PathVariable("roleId") String id) {
        Menu menu = menuService.getById(id);
        return success(menu);
    }

    @PreAuth
    @ApiOperation("新增菜单")
    @PostMapping
    public ApiResponses<Void> create(@RequestBody @Validated(value = MenuPARM.Create.class) MenuPARM menuPARM) {
        Menu menu = menuPARM.convert(Menu.class);
        ApiAssert.isTrue(ErrorCodeEnum.BAD_ADD_FAILURE, menuService.save(menu));
        return success();
    }

    @PreAuth
    @ApiOperation("修改菜单")
    @PutMapping("/{roleId}")
    public ApiResponses<Void> updateById(@PathVariable("roleId") String id, @RequestBody MenuPARM menuPARM) {
        menuPARM.setId(id);
        Menu updateMenu = menuPARM.convert(Menu.class);
        ApiAssert.isTrue(ErrorCodeEnum.BAD_UPDATE_FAILURE, menuService.updateById(updateMenu));
        return success();
    }

    @PreAuth
    @ApiOperation("删除菜单")
    @DeleteMapping("/{roleId}")
    public ApiResponses<Void> deleteById(@PathVariable("roleId") String id) {
        menuService.delMenu(id);
        return success();
    }

}

